<?php
/**
 *     
 *  生成订单 
 */
//require_once("IapppayCpSyncForPHP/base.php");
require_once("alipay/config.php");

class AliABPay extends APIBase {
	public $tag = "ApplyABPay";
	
	public function before() {
		$this->initMysql();
		return true;
	}
		
	//生成随机24位订单号
	protected function createOrderId ($length = 24) {
		$seed=md5(microtime());
		$pwd='';
		for($i=0;$i<$length;$i++){
			$pwd.=$seed{mt_rand(0,31)};
		}
		$hash=md5($pwd);
		return substr($hash,0,$length);
	}
	
	protected function paraFilter($para) {
	  $str='';	
	  foreach($para as $key=>$val){
	     if($key=='sign_type' || $key == 'sign'){
		   continue;
		  }
	   else{
	     if($str ==''){
		   $str =$key.'='.'"'.$val.'"';
	     }else{
		   $str =$str.'&'.$key.'='.'"'.$val.'"';
		 }	
		
	     }
        }
		return $str;
    }
	
    protected function argSort($para) {
		ksort($para);
		reset($para);
		return $para;
     }
    //RSA签名
    protected function sign($data) {
	
	   //读取私钥文件
	   //$sign = 111;
	   $priKey =  file_get_contents("C:/wamp/vhost/fksg/zjhapi/interface/1.5.1/rsa_private_key.pem");//私钥文件路径
	  //转换为openssl密钥，必须是没有经过pkcs8转换的私钥
	   $res = openssl_get_privatekey($priKey);
	  //调用openssl内置签名方法，生成签名$sign
	   openssl_sign($data, $sign, $res);
	  //释放资源 
	   openssl_free_key($res);
	   //base64编码
	   $sign = base64_encode($sign);
	   return $sign;
	 
	}


     	
	public function logic() {
		/*if (!isset($this->param['version'])) {
			$this->returnError(310, "param must be needed");
		}
*/      
       
		if (!isset($this->param['goodsid'])) {
			$this->returnError(310, "goodsid must be needed");
		}
		if (!isset($this->param['pay_type'])) {
			$this->returnError(310, "pay_type must be needed");
		}

		$where['id'] = (int)$this->param['goodsid'];
		$good = $this->mysql->select('goods','*',$where);
        if($good[0]['apple_id']){$apple_id = $good[0]['apple_id'];}else{$apple_id = 0;}
		if(!count($good)) {     
			$this->returnError(310, "goodsid is not exists");
		}

		$payinfo['uid'] = (int) $this->uid;
		$payinfo['price'] = (float) $good[0]['rmb'];
		$payinfo['pay_type'] = (int) $this->param['pay_type'];
		$payinfo['goodsid'] = (int) $this->param['goodsid'];
		$payinfo['version'] = 0;
		$payinfo['create_time'] = time();
		$payinfo['type'] = 0;
		$payinfo['is_send'] = 0;
		$payinfo['orderid'] = $this->createOrderId();
		$sign  = $this->mysql->insert('applypay', $payinfo);

		if ($sign) {
			//其它 购买方式
			if((int) $this->param['pay_type']==1){
				/*global $cpvkey;
				$data = array();
				$data['cporderid'] = $payinfo['orderid'];
				$data['price'] = (int)($payinfo['price']*100);
				$data['cpprivateinfo'] = "cpprivateinfo123456";
				$data['notifyurl'] = stripslashes(Config::$ab_pay_confing["notify_url"]);
				$data['appuserid'] = (string)$payinfo['uid'];
				$data['appid'] = Config::$ab_pay_confing["app_id"];
				$data['waresid'] = (int)$payinfo['goodsid'];
				$reqData = composeReq($data, $cpvkey);*/
				//$this->returnData($reqData);
				$ali = array(
					  'service' => 'mobile.securitypay.pay',
					  'partner' => Alionfig::$partner,// 签约合作者身份ID
					  '_input_charset' => 'utf-8',
					  'sign_type' => 'RSA',
					  'sign' => '',
					  'notify_url' => Config::$alipay_notify_url,//回调地址
					  'out_trade_no' => $payinfo['orderid'],//商户网站唯一订单号
					  'subject' => $good[0]['name'],//商品名称
					  'payment_type' => 1,//支付类型
					  'seller_id' => Alionfig::$seller_id,//支付宝账号
					  'total_fee' => (float) $good[0]['rmb'],//总金额
					  'body' => '',//商品详情
				);
                $ali = $this->argSort($ali);

                $str = $this->paraFilter($ali);
                $sign = urlencode($this->sign($str));
                $str = $str.'&sign='.'"'.$sign.'"'.'&sign_type='.'"'.$ali['sign_type'].'"';//传给支付宝接口的数据

				$this->returnData(array('orderinfo'=>$str,'notifyurl'=>''));
				
			//ios 购买	
			}elseif((int) $this->param['pay_type']==2){
				
				$str = "0#$payinfo[orderid]#$payinfo[price]#$apple_id";
				Config::$logger->info($this->tag, $str);
				
				$this->returnData(array('orderinfo'=>$str,'notifyurl'=>stripslashes(Config::$apple_pay_confing["apple_notify_url"])));
			}
			
		} else {
			$this->returnError(301,'create order failed!');
		}
	}
    
	public function after() {
		$this->deinitMysql();
	}
}

?>
